#include "stdafx.h"
#include "LFEventHandler.h"
#include "Guard.h";

namespace Network{
	ThreadMutex iSync;

	LFEventHandler::LFEventHandler(EventHandler *eh, LFThreadPool *tp) : eventHandler(eh), threadPool(tp)
	{
		SetHandle( eh->GetHandle() );
		
	}

	LFEventHandler::~LFEventHandler(void)
	{
		delete this->eventHandler;
	}

	void LFEventHandler::HandleEvent(HANDLE h, EventType et)
	{
		Guard guard(iSync);
		//deactivate the handle
		threadPool->DeactivateHandle(h, et);
		threadPool->PromoteNewLeader();
		
		eventHandler->HandleEvent(h, et);
		
		//reactivate the handle
		threadPool->ActivateHandle(h, et);
	}
	/*
	void LFEventHandler::handle_event()
	{
		//Sync pool
		setStatus(SUSPENDED);
		this->threadPool->PromoteNewLeader();

		//READ DATA
		//FROM SELECT REACTOR

		int dataReceived = 0;
		char buffer[64];

		ZeroMemory(buffer, sizeof(buffer));

		SOCK_Stream stream;
		SOCK_Acceptor socket = SOCK_Acceptor(this->getHandle());

		//Accept the connection from the socket stream
		socket.accept(stream);
		fprintf(stdout, "Accepted connection from handler [0x%x]\n", socket.get_handle());

		stream.receive(buffer, 2, 0);

		// all messages have the following structure:
		// EventType	data[0]		-> type of event 
		// (byte)		data[1]		-> size of the rest of the data structure
		// the handlers take care of parsing the rest of the message

		// find the event type to be able to select the correct handler
		EventType eventType = (EventType)(buffer[0]);

		// find the message size 
		u_int msgSize = buffer[1];
		char* message = (char*) malloc(sizeof(char)*msgSize);
		dataReceived = stream.receive(message,msgSize,0);

		// TODO concatenate buffer[0] and buffer[1] with char* message
		char* buf = (char*) malloc(sizeof(char)*msgSize + sizeof(buffer[0]) + sizeof(buffer[1]));				
		ZeroMemory(buf, sizeof(buf));
		buf[0] = buffer[0];
		buf[1] = buffer[1];

		//memcpy(message, textPtr, s);
		for (u_int i = 0; i < (sizeof(char)*msgSize); i++)
		{
			buf[i+2] = message[i];
		}

		if (dataReceived == msgSize && dataReceived > 0)
		{

			printf("(dataReceived == msgSize && dataReceived > 0\n");
			//TODO: REDO THIS

			//for (int k = 0 ; k < handlers->count; ++k)
			//{
			//	//For all the handlers, check if they are of the given eventtype
			//	if (handlers->handlesArray[k]->getType()==eventType)
			//	{
			//		//Handle event
			//		std::string response = handlers->handlesArray[k]->handle((unsigned char*)buf);							
			//		const char * c = response.c_str();							
			//		stream.send(c, response.size() + 1,0);
			//	}
			//}
		}
		else {
			fprintf(stdout, "Error in receiving message from client \n");
		}

		this->threadPool->ActivateHandle(this);
	}
	*/
}